package com.yxt.admin.controller;

import com.yxt.admin.config.ResourceServerConfig;
import com.yxt.admin.dto.UserDto;
import com.yxt.admin.entity.AuthToken;
import com.yxt.admin.entity.LoginBody;
import com.yxt.admin.entity.SysMenu;
import com.yxt.admin.entity.SysUser;
import com.yxt.admin.service.ISysMenuService;
import com.yxt.admin.service.LoginService;
import com.yxt.admin.service.impl.SysPermissionService;
import com.yxt.common.constant.Constant;
import com.yxt.common.utils.ServletUtils;
import com.yxt.common.utils.cookie.CookieUtil;
import com.yxt.common.utils.redis.RedisCache;
import com.yxt.common.utils.sign.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.yxt.common.utils.ajax.R;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysPermissionService permissionService;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    //Cookie生命周期
    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @Autowired
    private ISysMenuService menuService;

    /**
     * 密码模式  认证.
     * @param loginBody
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody LoginBody loginBody) {
        //登录 之后生成令牌的数据返回
        AuthToken authToken = loginService.login(loginBody.getUsername(),
                loginBody.getPassword(),
                loginBody.getCode(),
                loginBody.getUuid());
        //设置到cookie中
        // saveCookie(authToken.getAccessToken());
        //设置到cookie中
        saveCookie("Authorization",authToken.getAccessToken(),authToken.getExpiresIn().intValue());
        //保存refreshToken
        saveCookie("refreshToken",authToken.getRefreshToken(),2592000);
        return R.ok().put("data",authToken);
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public R getInfo()
    {

       OAuth2AuthenticationDetails authentication = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        Map<String, String> stringStringMap = JwtUtil.decodeToken(authentication.getTokenValue(), ResourceServerConfig.PUBLIC_KEY);
        String userId = String.valueOf(stringStringMap.get("userId"));
        UserDto userDto = redisCache.getCacheObject(Constant.USER_ACCOUNT_KEY+userId);

        SysUser user = userDto.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        return R.ok().put("user", user).put("roles", roles).put("permissions", permissions);
    }

    private void saveCookie(String tokenName,String takenValue,int time){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/",tokenName,takenValue,time,false);
    }

    @PostMapping("/logout")
    public R logout() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response,cookieDomain,"/","Authorization",null,0,false);
        CookieUtil.addCookie(response,cookieDomain,"/","refreshToken",null,0,false);

        return com.yxt.common.utils.ajax.R.ok();

    }


    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public R getRouters()
    {

        OAuth2AuthenticationDetails authentication = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        Map<String, String> stringStringMap = JwtUtil.decodeToken(authentication.getTokenValue(), ResourceServerConfig.PUBLIC_KEY);
        String userId = String.valueOf(stringStringMap.get("userId"));
        UserDto userDto = redisCache.getCacheObject(Constant.USER_ACCOUNT_KEY+userId);


        // 用户信息
        SysUser user = userDto.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        R data = R.ok().put("data", menuService.buildMenus(menus));
        return data;
    }
}
